package me.send.business.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.send.framework.util.MD5Util;

public class BusinessMain {

	
	public static void business() throws Exception {
		
	}
	
	/**
	 * 支付宝支付完成以后，当前窗口会从支付宝的页面跳转回这个页面。该页面称作“返回页”，
	 * 是同步被支付宝服务器所调用，可当作是支付完成后的提示信息页，如“您的某某某订单，多少金额已支付成功”。
	 */
	public void AlipayReturn(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
		// String alipayNotifyURL =
		// "http://notify.alipay.com/trade/notify_query.do?";//此路径是在上面链接地址无法起作用时替换使用。
		alipayNotifyURL = alipayNotifyURL
				+ "&partner=2088002302055380&notify_id="
				+ request.getParameter("notify_id");
		// 获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
		String responseTxt = check(alipayNotifyURL);
		// 获得POST 过来参数设置到新的requestParams中
		Map requestParams = request.getParameterMap();
		List keys = new ArrayList(requestParams.keySet());
		Collections.sort(keys);
		StringBuffer content = new StringBuffer();
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			if (!key.equals("") && !key.equals("sign")
					&& !key.equals("sign_type")) {
				content.append((String) keys.get(i));
				content.append("=");
				content.append((String) requestParams.get((String) keys.get(i)));
				if (i != keys.size() - 1) {
					content.append("&");
				}
			}
		}
		String securityCode = "7nj9sczcnfc4n8366j46mrzsbqjksmzn";// securityCode(安全码);
		content.append(securityCode);
		String mysign = MD5Util.MD5(content.toString());
		System.out.println("--------------------------content=" + content);
		System.out.println("--------------------------mysign=" + mysign);
		System.out.println("--------------------------sign=" + request.getParameter("sign"));
	}

	/**
	 * 
	 * 通知返回URL,仅适用于异步返回处理结果的接口。
	 * 
	 * 有些服务是无法立即返回处理结果的，
	 * 
	 * 那么需要通过这个URL将处理结果异步返回给合作伙伴
	 * 
	 */
	public void AlipayNotify(HttpServletRequest request) throws Exception {
		String alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify";
		// String alipayNotifyURL =
		// "http://notify.alipay.com/trade/notify_query.do?";//此路径是在上面链接地址无法起作用时替换使用。
		alipayNotifyURL = alipayNotifyURL
				+ "&partner=2088002302055380&notify_id="
				+ request.getParameter("notify_id");
		// 获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
		String responseTxt = check(alipayNotifyURL);
		// 获得POST 过来参数设置到新的requestParams中
		Map requestParams = request.getParameterMap();
		List keys = new ArrayList(requestParams.keySet());
		Collections.sort(keys);
		StringBuffer content = new StringBuffer();
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			if (!key.equals("") && !key.equals("sign")
					&& !key.equals("sign_type")) {
				content.append((String) keys.get(i));
				content.append("=");
				content.append((String) requestParams.get((String) keys.get(i)));
				if (i != keys.size() - 1) {
					content.append("&");
				}
			}
		}
		String securityCode = "7nj9sczcnfc4n8366j46mrzsbqjksmzn";// securityCode(安全码);
		content.append(securityCode);
		String mysign = MD5Util.MD5(content.toString());
		System.out.println("--------------------------content=" + content);
		System.out.println("--------------------------mysign=" + mysign);
		System.out.println("--------------------------sign="
				+ request.getParameter("sign"));
	}

	/**
	 * @param myUrl
	 * 
	 * @param url
	 * 
	 * @return 获取url内容
	 */
	public static String check(String urlvalue) {
		String inputLine = "";
		try {
			URL url = new URL(urlvalue);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream()));
			String stTemp = "";
			while ((stTemp = in.readLine()) != null) {
				System.out.println(stTemp);
				inputLine = inputLine + stTemp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputLine;
	}

	public static void submitAlipayUrl() throws Exception {
		
		String orderNo = "No100001010101";// 订单编号
		HashMap hm = new HashMap();
		hm.put("_input_charset", "utf-8");// 采用相同的编码方式
		hm.put("body", "企鹅个性化图书订单，订单号：" + orderNo);// 填写在跳到支付宝页面上显示的付款内容信息
		hm.put("notify_url",
				"http://127.0.0.1:8888/mypenguin/orders.do?method=AlipayNotify");// 客户付款后,支付宝调用的页面
		hm.put("out_trade_no", orderNo);// 外部交易号,最好具有唯一性,在获取支付宝发来的付款信息时使用.
		hm.put("partner", "2088002302055380");// partnerId(合作伙伴ID)
		// hm.put("agent", "2088002302055380");// partnerId(合作伙伴ID)
		hm.put("payment_type", "1");// 支付类型 1=商品购买,2=服务购买,...
		// hm.put("price", "178.00");// 订单金额信息
		hm.put("total_fee", "178.00");// 订单金额和信息
		// hm.put("quantity", "1");// 订单商品数量,一般都是写1,它是按照整个订单包来计算
		hm.put("return_url",
				"http://127.0.0.1:8888/mypenguin/orders.do?method=AlipayReturn");// 客户付款成功后,显示给客户的页面
		hm.put("show_url",
				"http://127.0.0.1:8888/mypenguin/books.do?method=list&kindId=1");// 展示地址，即在支付页面时，商品名称旁边的“详情”的链接地址。
		hm.put("seller_email", "monicali_7766@sina.com");// 你的支付宝账户email
		hm.put("service", "create_direct_pay_by_user");// create_direct_pay_by_user=直接付款,trade_create_by_buyer=担保付款
		hm.put("subject", "企鹅个性化图书订单号：" + orderNo);// 填写在跳到支付宝页面上显示的付款标题信息
		String payGateway = "https://www.alipay.com/cooperate/gateway.do";// 跳转到支付宝的url头
		String securityCode = "7nj9sczcnfc4n8366j46mrzsbqjksmzn";// securityCode(安全码);
		String sign = makeUrl(hm, securityCode, "utf-8", payGateway);// securityCode(安全码);
		
		hm.put("sign", sign);
		hm.put("sign_type", "MD5");
		
		System.out.println("end ...........................................");
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		submitAlipayUrl();
	}

	/**
	 * 根据传入的参数生成Alipay的支付URL
	 * 
	 * @param hm
	 *            参数值
	 * @param securityCode
	 *            安全码
	 * @param charset
	 *            编码
	 * @param payGateway
	 *            支付宝gateway
	 * @return
	 */
	public static String makeUrl(HashMap hm, String securityCode,
			String charSet, String payGateway) throws Exception {
		List keys = new ArrayList(hm.keySet());
		Collections.sort(keys);// 支付宝要求参数必须按字母排序
		StringBuffer content = new StringBuffer();
		for (int i = 0; i < keys.size(); i++) {
			content.append((String) keys.get(i));
			content.append("=");
			content.append((String) hm.get((String) keys.get(i)));
			if (i != keys.size() - 1) {
				content.append("&");
			}
		}
		content.append(securityCode);
		String sign = MD5Util.MD5(content.toString()); // MD5加密
		return sign;
	}

}
